<template>
  <div class="main-quest-flow">
    <!-- 章节标题和进度 -->
    <div class="chapter-header">
      <div class="chapter-info">
        <h1 class="chapter-title">{{ currentChapter.name }}</h1>
        <p class="chapter-description">{{ currentChapter.description }}</p>
      </div>
      
      <div class="progress-info">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
        </div>
        <span class="progress-text">{{ currentLevel }}/{{ totalLevels }}</span>
      </div>
    </div>

    <!-- 流程状态显示 -->
    <div class="flow-status">
      <div class="status-steps">
        <div class="step" :class="{ active: currentStep === 'plot', completed: completedSteps.includes('plot') }">
          <div class="step-icon">📖</div>
          <span class="step-label">剧情</span>
        </div>
        
        <div class="step" :class="{ active: currentStep === 'preparation', completed: completedSteps.includes('preparation') }">
          <div class="step-icon">⚔️</div>
          <span class="step-label">准备</span>
        </div>
        
        <div class="step" :class="{ active: currentStep === 'battle', completed: completedSteps.includes('battle') }">
          <div class="step-icon">⚡</div>
          <span class="step-label">战斗</span>
        </div>
        
        <div class="step" :class="{ active: currentStep === 'reward', completed: completedSteps.includes('reward') }">
          <div class="step-icon">🎁</div>
          <span class="step-label">奖励</span>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 剧情播放阶段 -->
      <div v-if="currentStep === 'plot'" class="plot-stage">
        <PlotPlayer
          :chapter-id="chapterId"
          :level="currentLevel"
          @plot-finished="handlePlotFinished"
          @skip-plot="handleSkipPlot"
        />
      </div>

      <!-- 战斗准备阶段 -->
      <div v-if="currentStep === 'preparation'" class="preparation-stage">
        <div class="enemy-preview">
          <h3 class="stage-title">即将面对的敌人</h3>
          
          <div class="enemy-formation" v-if="enemyFormation.length > 0">
            <EnemyCard
              v-for="enemy in enemyFormation"
              :key="enemy.id"
              :enemy="enemy"
              :show-actions="false"
              size="small"
            />
          </div>
          
          <!-- BOSS预览 -->
          <div class="boss-preview" v-if="bossInfo">
            <h4 class="boss-title">章节BOSS</h4>
            <EnemyCard
              :enemy="bossInfo"
              :show-actions="false"
              size="normal"
            />
          </div>
        </div>

        <div class="preparation-actions">
          <button class="action-btn secondary" @click="goBack">
            返回
          </button>
          <button class="action-btn primary" @click="startBattle" :disabled="isLoading">
            <span v-if="isLoading">准备中...</span>
            <span v-else>开始战斗</span>
          </button>
        </div>
      </div>

      <!-- 战斗阶段 -->
      <div v-if="currentStep === 'battle'" class="battle-stage">
        <div class="battle-info">
          <h3 class="stage-title">战斗进行中</h3>
          <p class="battle-description">正在加载战斗场景...</p>
        </div>
        
        <div class="battle-loading">
          <div class="loading-spinner"></div>
          <p>初始化战斗数据中...</p>
        </div>

        <!-- 战斗数据展示 -->
        <div class="battle-data" v-if="battleData">
          <div class="battle-participants">
            <div class="player-side">
              <h4>我方阵容</h4>
              <div class="formation">
                <div v-for="unit in battleData.playerFormation" :key="unit.id" class="unit-card">
                  <img :src="unit.avatar" :alt="unit.name" />
                  <span>{{ unit.name }}</span>
                </div>
              </div>
            </div>
            
            <div class="enemy-side">
              <h4>敌方阵容</h4>
              <div class="formation">
                <div v-for="unit in battleData.enemyFormation" :key="unit.id" class="unit-card">
                  <img :src="unit.avatar" :alt="unit.name" />
                  <span>{{ unit.name }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 奖励阶段 -->
      <div v-if="currentStep === 'reward'" class="reward-stage">
        <div class="reward-info">
          <h3 class="stage-title">战斗胜利！</h3>
          <div class="victory-animation">🎉</div>
        </div>
        
        <div class="rewards-list" v-if="rewards.length > 0">
          <h4>获得奖励</h4>
          <div class="reward-items">
            <div v-for="reward in rewards" :key="reward.id" class="reward-item">
              <img :src="reward.icon" :alt="reward.name" />
              <span class="reward-name">{{ reward.name }}</span>
              <span class="reward-amount">x{{ reward.amount }}</span>
            </div>
          </div>
        </div>

        <div class="reward-actions">
          <button class="action-btn primary" @click="continueQuest">
            继续冒险
          </button>
          <button class="action-btn secondary" @click="returnToMap">
            返回地图
          </button>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <div class="error-content">
        <span class="error-icon">⚠️</span>
        <span class="error-text">{{ error }}</span>
        <button class="error-close" @click="clearError">×</button>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner large"></div>
        <p class="loading-text">{{ loadingText }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import PlotPlayer from './PlotPlayer.vue'
import EnemyCard from './EnemyCard.vue'
import { getLevelEnemies, getBossInfo, startMainBattle } from '@/api/mainquest'

export default {
  name: 'MainQuestFlow',
  components: {
    PlotPlayer,
    EnemyCard
  },
  props: {
    chapterId: {
      type: Number,
      required: true
    },
    levelId: {
      type: Number,
      required: true
    },
    chapterInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      currentStep: 'plot', // plot, preparation, battle, reward
      completedSteps: [],
      currentLevel: 1,
      totalLevels: 10,
      enemyFormation: [],
      bossInfo: null,
      battleData: null,
      rewards: [],
      isLoading: false,
      loadingText: '加载中...',
      error: null
    }
  },
  computed: {
    currentChapter() {
      return this.chapterInfo || {
        name: '未知章节',
        description: '章节描述加载中...'
      }
    },
    
    progressPercentage() {
      return (this.currentLevel / this.totalLevels) * 100
    }
  },
  mounted() {
    this.initializeQuest()
  },
  methods: {
    // 初始化任务
    async initializeQuest() {
      try {
        this.isLoading = true
        this.loadingText = '初始化任务数据...'
        
        // 设置当前关卡
        this.currentLevel = this.levelId
        
        // 预加载敌人数据
        await this.loadEnemyData()
        
        // 如果是BOSS关卡，加载BOSS信息
        if (this.isBossLevel()) {
          await this.loadBossData()
        }
        
      } catch (error) {
        console.error('初始化任务失败:', error)
        this.error = '任务初始化失败，请重试'
      } finally {
        this.isLoading = false
      }
    },
    
    // 加载敌人数据
    async loadEnemyData() {
      try {
        const response = await getLevelEnemies({
          chapterId: this.chapterId,
          level: this.currentLevel
        })
        
        if (response.code === 0) {
          this.enemyFormation = response.data.enemies || []
        } else {
          throw new Error(response.msg || '获取敌人数据失败')
        }
      } catch (error) {
        console.error('加载敌人数据失败:', error)
        throw error
      }
    },
    
    // 加载BOSS数据
    async loadBossData() {
      try {
        const response = await getBossInfo({
          chapterId: this.chapterId,
          level: this.currentLevel
        })
        
        if (response.code === 0) {
          this.bossInfo = response.data.boss
        } else {
          console.warn('获取BOSS数据失败:', response.msg)
        }
      } catch (error) {
        console.error('加载BOSS数据失败:', error)
      }
    },
    
    // 判断是否为BOSS关卡
    isBossLevel() {
      // 通常每章的最后一关是BOSS关卡
      return this.currentLevel % 10 === 0
    },
    
    // 剧情播放完成
    handlePlotFinished() {
      this.completedSteps.push('plot')
      this.currentStep = 'preparation'
    },
    
    // 跳过剧情
    handleSkipPlot() {
      this.completedSteps.push('plot')
      this.currentStep = 'preparation'
    },
    
    // 开始战斗
    async startBattle() {
      try {
        this.isLoading = true
        this.loadingText = '初始化战斗...'
        
        const response = await startMainBattle({
          chapterId: this.chapterId,
          level: this.currentLevel
        })
        
        if (response.code === 0) {
          this.battleData = response.data
          this.completedSteps.push('preparation')
          this.currentStep = 'battle'
          
          // 模拟战斗过程
          await this.simulateBattle()
        } else {
          throw new Error(response.msg || '开始战斗失败')
        }
      } catch (error) {
        console.error('开始战斗失败:', error)
        this.error = '战斗初始化失败，请重试'
      } finally {
        this.isLoading = false
      }
    },
    
    // 模拟战斗过程
    async simulateBattle() {
      // 这里应该集成实际的战斗逻辑
      // 目前只是模拟战斗结果
      
      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟战斗胜利
          this.completedSteps.push('battle')
          this.currentStep = 'reward'
          
          // 模拟奖励
          this.rewards = [
            {
              id: 1,
              name: '经验值',
              icon: '/static/images/rewards/exp.png',
              amount: 100
            },
            {
              id: 2,
              name: '金币',
              icon: '/static/images/rewards/gold.png',
              amount: 50
            }
          ]
          
          resolve()
        }, 3000) // 3秒后战斗结束
      })
    },
    
    // 继续任务
    continueQuest() {
      if (this.currentLevel < this.totalLevels) {
        // 进入下一关
        this.currentLevel++
        this.resetFlow()
        this.initializeQuest()
      } else {
        // 章节完成
        this.$emit('chapter-completed', {
          chapterId: this.chapterId,
          level: this.currentLevel
        })
      }
    },
    
    // 返回地图
    returnToMap() {
      this.$emit('return-to-map')
    },
    
    // 返回上一步
    goBack() {
      if (this.currentStep === 'preparation') {
        this.currentStep = 'plot'
        this.completedSteps = this.completedSteps.filter(step => step !== 'plot')
      }
    },
    
    // 重置流程
    resetFlow() {
      this.currentStep = 'plot'
      this.completedSteps = []
      this.enemyFormation = []
      this.bossInfo = null
      this.battleData = null
      this.rewards = []
      this.error = null
    },
    
    // 清除错误
    clearError() {
      this.error = null
    }
  }
}
</script>

<style scoped>
.main-quest-flow {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #ffffff;
  position: relative;
}

.chapter-header {
  padding: 20px;
  background: rgba(0, 0, 0, 0.3);
  border-bottom: 2px solid rgba(255, 255, 255, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chapter-info {
  flex: 1;
}

.chapter-title {
  font-size: 28px;
  font-weight: bold;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.chapter-description {
  font-size: 16px;
  color: #cccccc;
  margin: 0;
  line-height: 1.5;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.progress-bar {
  width: 200px;
  height: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50, #8BC34A);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  font-weight: bold;
  color: #ffd700;
}

.flow-status {
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
}

.status-steps {
  display: flex;
  justify-content: center;
  gap: 40px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  opacity: 0.5;
  transition: all 0.3s ease;
}

.step.active {
  opacity: 1;
  transform: scale(1.1);
}

.step.completed {
  opacity: 0.8;
}

.step-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.step.active .step-icon {
  background: rgba(255, 215, 0, 0.2);
  border-color: #ffd700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.3);
}

.step.completed .step-icon {
  background: rgba(76, 175, 80, 0.2);
  border-color: #4CAF50;
}

.step-label {
  font-size: 14px;
  font-weight: bold;
  color: #cccccc;
}

.step.active .step-label {
  color: #ffd700;
}

.step.completed .step-label {
  color: #4CAF50;
}

.content-area {
  padding: 30px;
  min-height: 500px;
}

.stage-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #ffd700;
}

.preparation-stage {
  max-width: 1200px;
  margin: 0 auto;
}

.enemy-preview {
  margin-bottom: 30px;
}

.enemy-formation {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
}

.boss-preview {
  text-align: center;
}

.boss-title {
  font-size: 20px;
  color: #f44336;
  margin-bottom: 20px;
}

.preparation-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.battle-stage {
  text-align: center;
}

.battle-loading {
  margin: 40px 0;
}

.battle-data {
  margin-top: 30px;
}

.battle-participants {
  display: flex;
  justify-content: space-around;
  gap: 40px;
}

.player-side, .enemy-side {
  flex: 1;
}

.formation {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
}

.unit-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  min-width: 80px;
}

.unit-card img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.unit-card span {
  font-size: 12px;
  color: #cccccc;
}

.reward-stage {
  text-align: center;
  max-width: 600px;
  margin: 0 auto;
}

.victory-animation {
  font-size: 60px;
  margin: 20px 0;
  animation: bounce 1s infinite;
}

.rewards-list {
  margin: 30px 0;
}

.reward-items {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.reward-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  min-width: 100px;
  border: 2px solid rgba(255, 215, 0, 0.3);
}

.reward-item img {
  width: 40px;
  height: 40px;
  object-fit: cover;
}

.reward-name {
  font-size: 14px;
  color: #ffffff;
}

.reward-amount {
  font-size: 12px;
  color: #ffd700;
  font-weight: bold;
}

.reward-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.action-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.action-btn.primary {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
}

.action-btn.primary:hover {
  background: linear-gradient(135deg, #45a049, #3d8b40);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border-color: rgba(255, 255, 255, 0.4);
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.error-content {
  background: rgba(244, 67, 54, 0.9);
  color: white;
  padding: 15px 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.3s ease;
}

.error-icon {
  font-size: 18px;
}

.error-text {
  flex: 1;
}

.error-close {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  text-align: center;
  color: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #ffd700;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

.loading-spinner.large {
  width: 60px;
  height: 60px;
  border-width: 6px;
}

.loading-text {
  font-size: 16px;
  color: #cccccc;
}

/* 动画效果 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chapter-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .chapter-title {
    font-size: 24px;
  }
  
  .progress-bar {
    width: 150px;
  }
  
  .status-steps {
    gap: 20px;
  }
  
  .step-icon {
    width: 40px;
    height: 40px;
    font-size: 16px;
  }
  
  .content-area {
    padding: 20px 15px;
  }
  
  .stage-title {
    font-size: 20px;
  }
  
  .battle-participants {
    flex-direction: column;
    gap: 20px;
  }
  
  .action-btn {
    padding: 10px 20px;
    font-size: 14px;
    min-width: 100px;
  }
  
  .reward-actions, .preparation-actions {
    flex-direction: column;
    align-items: center;
  }
}
</style>